<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use App\Http\Common\JsonResponse as MyJsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class ResponseHandle
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->headers->set('accept', 'application/json');
        $response = $next($request);
        if ($response instanceof MyJsonResponse) {
            return $response;
        }

        if ($response instanceof JsonResponse) {
            $oriData = $response->getData();
            if (isset($oriData->msg) || isset($oriData->exception)) {
                return $response;
            }

            $message = [
                'status' => 0,
                'message' => 'success'
            ];

            $data['data'] = ($oriData->data ?? []) ? $oriData->data : $oriData;

            if ($oriData->current_page ?? '') {
                $data['meta'] = [
                    'total' => $oriData->total ?? 0,
                    'per_page' => (int)$oriData->per_page ?? 0,
                    'current_page' => $oriData->current_page ?? 0,
                    'last_page' => $oriData->last_page ?? 0
                ];
                $data['data'] = $oriData->data;
            }

            if ($oriData->meta ?? '') {
                $data['meta'] = [
                    'total' => $oriData->meta->total ?? 0,
                    'per_page' => (int)$oriData->meta->per_page ?? 0,
                    'current_page' => $oriData->meta->current_page ?? 0,
                    'last_page' => $oriData->meta->last_page ?? 0
                ];
                $data['data'] = $oriData->data;
            }
            $temp = array_merge($message, $data);
            $response = $response->setData($temp);
            Log::debug('Response Success: ' . json_encode($response->getData()));
            Log::debug(PHP_EOL);
            return $response;
        }
        return $response;
    }
}
